package com.yuanhua.sim.netty.serve.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yuanhua.auth.server.utils.JwtTokenServerUtils;
import com.yuanhua.core.base.entity.*;
import com.yuanhua.core.utils.SpringUtils;
import com.yuanhua.sim.netty.utils.NettyAttrUtil;
import com.yuanhua.sim.netty.utils.SessionUtils;
import com.yuanhua.sim.service.HreatBeatService;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@ChannelHandler.Sharable
@Slf4j
public class ServerChatHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Long userId = SessionUtils.getUserId(ctx.channel());
        log.info("用户"+userId +"掉线。连接关闭");
        super.channelInactive(ctx);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有客户端连接进来了");
        ctx.channel().config().setWriteBufferHighWaterMark(2048*2048);
        super.channelActive(ctx);
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, WebSocketFrame msg) throws Exception {
        TextWebSocketFrame textWebSocketFrame = (TextWebSocketFrame) msg;
        ByteBuf bytebuf = textWebSocketFrame.content();
        //从content中写入缓冲
        String content = bytebuf.toString(StandardCharsets.UTF_8);
        System.out.println("消息-------"+content);
        JSONObject jsonObject = JSONObject.parseObject(content);
        //handWebsocketFrame(channelHandlerContext, msg);
        String msgRecive = "Helloworld";
        ByteBuf byteBuf = getByteBuf(channelHandlerContext, msgRecive, 1L, "1");

        channelHandlerContext.writeAndFlush(new TextWebSocketFrame(byteBuf));
    }


    public ByteBuf getByteBuf(ChannelHandlerContext ctx, String message, Long toUser, String fileType) {
        ByteBuf byteBuf = ctx.alloc().buffer();
        //User fromUser = SessionUtils.getUser(ctx.channel());
        JSONObject data = new JSONObject();
        data.put("type", 2);
        data.put("status", 200);
        JSONObject params = new JSONObject();
        params.put("message", message);
        params.put("fileType", fileType);
        params.put("fromUser", toUser);
        params.put("toUser", toUser);
        data.put("params", params);
        byte []bytes = data.toJSONString().getBytes(Charset.forName("utf-8"));
        byteBuf.writeBytes(bytes);
        return byteBuf;
    }



    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if(evt instanceof IdleStateEvent){
            IdleStateEvent idleStateEvent = (IdleStateEvent) evt;
            //读空闲事件
            if (idleStateEvent.state() == IdleState.READER_IDLE) {
                //处理业务，判断上一次时间距离现在多久，超过系统规定的时间就关闭连接，主要是给客户端一个机会；
                log.info("读空闲事件触发;即将关闭该连接");
                HreatBeatService h = SpringUtils.getBean(HreatBeatService.class);
                h.process(ctx);
            }
        }
        super.userEventTriggered(ctx, evt);
    }
}